<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin-top:20px;">
      <el-button type="primary" @click="dialogVisible = true">
        添加角色</el-button
      >

      <el-table :data="rolesList" style="width: 100%;margin-top:20px;" border>
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '']"
              v-for="(item, i1) in scope.row.children"
              :key="item.id"
            >
              <el-col :span="5">
                <el-tag closable @close="handleClose(item.id, scope.row)">
                  {{ item.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop']"
                  v-for="(item1, i2) in item.children"
                  :key="item1.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="handleClose(item1.id, scope.row)"
                    >
                      {{ item1.authName }}
                    </el-tag>
                  </el-col>

                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item2 in item1.children"
                      :key="item2.id"
                      closable
                      @close="handleClose(item2.id, scope.row)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#" width="60"> </el-table-column>
        <el-table-column label="角色名称" prop="roleName"> </el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"> </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRole(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delUser(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色弹框 -->
    <el-dialog title="添加角色" :visible.sync="dialogVisible" width="30%">
      <el-form
        ref="userForm"
        :rules="rules"
        :model="userForm"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="userForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="userForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色弹框 -->
    <el-dialog title="编辑角色" :visible.sync="editdialogVisible" width="30%">
      <el-form
        ref="editForm"
        :rules="rules"
        :model="editForm"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser(editForm.id)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  <!-- 分配权限对话框 -->
      <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%">
          <!-- 树形组件
          show-checkbox:显示复选框
          node-key:设置选中节点对应的值
          default-expand-all:是否默认展开所有节点
          :default-checked-keys 设置默认选中项的数组
          ref:设置引用 -->
          <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
          <span slot="footer" class="dialog-footer">
              <el-button @click="setRightDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="allotRights">确 定</el-button>
          </span>
      </el-dialog>
  </div>
</template>

<script>
export default {
  name: "",
  // 组件注册
  components: {},
  // 父组件传参
  props: {},
  // 变量声明
  data() {
    return {
      // 控制添加角色框显示隐藏
      dialogVisible: false,
      //   控制修改角色弹框显示隐藏
      editdialogVisible: false,
      // 控制分配角色显示隐藏
      setRightDialogVisible: false,
      rolesList: [],
      userForm: {
        roleName: "",
        roleDesc: "",
      },
      editForm: {
        roleName: "",
        roleDesc: "",
        id: "",
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 3, max: 9, message: "长度在 3 到 9 个字符", trigger: "blur" },
        ],
      },
      //权限树数据
      rightsList: [],
      //树形控件的属性绑定对象
      treeProps: {
        //通过label设置树形节点文本展示authName
        label: "authName",
        //设置通过children属性展示子节点信息
        children: "children",
      },
      //设置树形控件中默认选中的内容
      defKeys: [],
      //保存正在操作的角色id
      roleId: "",
    };
  },
  // Vue实例创建完成以后执行 数据可用
  created() {
    this.getroles();
  },
  // Vue模板挂载完毕以后执行  DOM节点加载完毕了（可以获取节点了）
  mounted() {},
  // keepalive 缓存进入执行
  activited() {},
  // vue组件更新完毕以后执行
  update() {},
  // 定义事件
  methods: {
    async getroles() {
      let res = await this.$axios.get("roles");
      let { meta, data } = res.data;
      //   console.log(meta, data);

      this.rolesList = data;
      //  console.log(this.rolesList)
    },
    addUser() {
      this.$refs.userForm.validate(async (valid) => {
        if (valid) {
          let { data: res } = await this.$axios.post("roles", this.userForm);
          //   console.log(res)
          if (res.meta.status == 201) {
            this.$message.success(res.meta.msg);
            this.dialogVisible = false;
            this.getroles();
            this.userForm = {};
          } else {
            this.$message.error(res.meta.msg);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.userForm.resetFields();
      this.dialogVisible = false;
    },
    // 删除角色
    delUser(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await this.$axios.delete("roles/" + id);
          this.getroles();

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    editRole(item) {
      this.editForm = item;
      this.editdialogVisible = true;
      this.getroles();
    },
    async editUser(id) {
      console.log(id);
      let res = await this.$axios.put(`roles/${id}`, this.editForm);
      console.log(res);
      let { meta } = res.data;
      if (meta.status == 200) {
        this.$message.success("更新成功");
        this.getroles();
        this.editdialogVisible = false;
      } else {
        this.$message.error(meta.msg);
      }
    },
    async handleClose(id, item) {
      // console.log(id,item)
      let res = await this.$axios.delete(`roles/${item.id}/rights/${id}`);
      console.log(res);
      if (res.data.meta.status == 200) {
        this.getroles();
        this.$message.success("删除成功");
      }
    },

    async showSetRightDialog(role) {
      //将role.id保存起来以供保存权限时使用
      this.roleId = role.id;  
      //获取所有权限的数据
      const { data: res } = await this.$axios.get('rights/tree')
      //如果返回状态为异常状态则报错并返回
      if (res.meta.status !== 200) return this.$message.error('获取权限树失败')
      //如果返回状态正常，将请求的数据保存在data中
      this.rightsList = res.data

      //调用getLeafKeys进行递归，将三级权限添加到数组中
      this.getLeafKeys(role, this.defKeys)
      //当点击分配权限按钮时，展示对应的对话框
      this.setRightDialogVisible = true
      console.log(this.defKeys)
    },
    getLeafKeys(node, arr) {
      //该函数会获取到当前角色的所有三级权限id并添加到defKeys中
      //如果当前节点不包含children属性，则表示node为三级权限
      if (!node.children) {
        return arr.push(node.id)
      }
      //递归调用
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    setRightDialogClose() {
      //当用户关闭树形权限对话框的时候，清除掉所有选中状态
      this.defKeys = []
    },
      async allotRights() {
      //当用户在树形权限对话框中点击确定，将用户选择的
      //权限发送请求进行更新

      //获取所有选中及半选的内容
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      //将数组转换为 , 拼接的字符串
      const idStr = keys.join(',')

      //发送请求完成更新
      const { data: res } = await this.$axios.post(
        `roles/${this.roleId}/rights`,
        { rids:idStr }
      )
      if (res.meta.status !== 200)
        return this.$message.error('分配权限失败')

      this.$message.success("分配权限成功")
      this.getroles();
      //关闭对话框
      this.setRightDialogVisible = false;
    }


  },
  // 过滤器
  filter: {},
  // 计算属性
  computed: {},
  // 监听属性
  watch: {},
};
</script>

<style scoped>
.el-tag {
  margin-top: 10px;
  margin-right: 10px;
}
</style>
